/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.sge.sched;

import jp.aist.gtrc.plus.scheduler.specific.sge.status.SGEACL;
import jp.aist.gtrc.plus.scheduler.specific.sge.status.SGEQueueStatus;
import jp.aist.gtrc.plus.scheduler.specific.sge.status.SGETaskStatus;
import jp.aist.gtrc.plus.scheduler.util.Checker;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;

public class SGEQueueChecker extends Checker<SGEQueueStatus> {

	private final SGETaskStatus task;
	private final SGEJobPEChecker peChecker;
	private final String owner;

	private SGEQueueChecker(SGETaskStatus task, SGEJobPEChecker peCheker,
			String owner) {

		this.task = task;
		this.peChecker = peCheker;
		this.owner = owner;

	}
	public SGEQueueChecker(SGETaskStatus task) {

		/*
		 * NOTE: isOK() is called many times, so make
		 * peChecker here for better performance.
		 */
		this(task, new SGEJobPEChecker(), null);

	}

	public SGEQueueChecker(String owner) {

		this(null, null, owner);

	}

	private boolean checkPE(SGEQueueStatus queue) {

		if (task == null) {
			return true;
		}

		String peName = task.getTargetParallelEnvName();
		if (TextUtil.isEmpty(peName)) {
			return true;
		}

		if (queue.hasParallelEnv(peName) == false) {
			return false;
		}

		return peChecker.isOK(task);

	}

	private boolean checkQueue(SGEQueueStatus queue) {

		SGEACL acl = queue.getAcl();
		if (task != null) {
			return acl.isAllowedTo(task.getOwner(), task.getTargetProjectName());
		} else {
			return acl.isAllowedToUser(owner);
		}

	}

	public boolean isOK(SGEQueueStatus queue) {

		return (checkPE(queue) && checkQueue(queue));

	}

}
